/*
 * Copyright 2012-2013 EZC Group S.A. RCS Luxembourg B140949
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yobidrive.y3.utils;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.yobidrive.y3.v1.client.http.Y3HttpClient;

/**
 * Helper class to manipulate XML Doc document.
 * 
 * Using JDOM would be easier but would add an additional
 * dependency to the API.
 *  
 * @author david
 *
 */
public class XMLUtils {
	static private final Logger logger = Logger.getLogger(XMLUtils.class);
	
	public static String getChildText(Node node, String childName) {
		if ( node instanceof Element ) return getChildText((Element) node, childName);
		NodeList nodeList = node.getChildNodes();
		if ( nodeList == null || nodeList.getLength() == 0) return "";
		for ( int i=0; i<nodeList.getLength(); i++) {
			Node current = nodeList.item(i);
			if ( childName.equals(current.getNodeName())) {
				return StringEscapeUtils.unescapeXml(current.getTextContent());
			}
		}
		return ""; //Not found
	}
	
	public static String getChildText(Element element, String childName) {
		if ( element == null ) return "";
		NodeList nodeList = element.getElementsByTagName(childName);
		if ( nodeList == null || nodeList.getLength() == 0) return "";
		return StringEscapeUtils.unescapeXml(nodeList.item(0).getTextContent()); 
	}
	
	public static Element getChildByName(Element element, String childName) {
		if ( element == null ) return null;
		NodeList nodeList = element.getElementsByTagName(childName);
		if ( nodeList == null || nodeList.getLength() ==0) return null;
		Node item = nodeList.item(0);
		if ( item == null || !(item instanceof Element)) return null;
		return (Element) item;
	}
	
	public static Element addChildText(Document doc, Element parent, String childName, String value) {
		Element newElt = doc.createElement(childName);
		newElt.setTextContent(value);
		parent.appendChild(newElt);
		return newElt;
	}
	
	
	
	public static int stringToInt(String str, int defaultValue) {
		if ( str == null || "".equals(str) )
			return defaultValue ;
		try {
			return Integer.parseInt(str) ;
		} catch ( Throwable th ) {
			return defaultValue ;
		}
	}
	
	public static long stringToLong(String str, long defaultValue) {
		if ( str == null || "".equals(str) )
			return defaultValue ;
		try {
			return Long.parseLong(str) ;
		} catch ( Throwable th ) {
			return defaultValue ;
		}
	}
	
	public static boolean stringToBoolean(String str, boolean defaultValue) {
		if ( str == null || "".equals(str) )
			return defaultValue ;
		return "true".equals(str) || "1".equals(str);
	}
	
	public static String elementToString(Element rootNode) {
		try {
			TransformerFactory transFactory = TransformerFactory.newInstance();
			Transformer transformer = transFactory.newTransformer();
			StringWriter buffer = new StringWriter();
			//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			transformer.transform(new DOMSource(rootNode), new StreamResult(buffer));
			return buffer.toString();
		} catch (Exception ex) {
			logger.error("Unable to convert element to string", ex);
			return null;
		}
	}
}
